package com.paw.es7.controller;

import com.alibaba.fastjson.JSON;
import com.paw.es7.domain.DayLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: lvzihai
 * @date: 2021/5/25
 **/
@Slf4j
@Api(tags = "ES搜索")
@RestController
public class DayLogController {

  @Autowired
  private ElasticsearchRestTemplate restTemplate;

  @ApiOperation("search")
  @GetMapping("/search")
  public Object search(){

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    boolQueryBuilder
        .filter(QueryBuilders.termQuery("appName.keyword","activity"))
        .filter(QueryBuilders.termQuery("level.keyword","ERROR"));

    NativeSearchQuery searchQuery = new NativeSearchQuery(boolQueryBuilder);
    log.info("query: {}",searchQuery.getQuery().toString());
    //索引名称规定 可在类上标注，ES会根据类标注生成索引IndexCoordinates
    SearchHits<DayLog> searchHits0 = restTemplate.search(searchQuery, DayLog.class);
    //索引不固定 以参数方式传入
    String indexName = "logs-2021.05.25";
    SearchHits<DayLog> searchHits = restTemplate.search(searchQuery, DayLog.class, IndexCoordinates.of(indexName));
    System.out.println(JSON.toJSONString(searchHits));

    return JSON.toJSONString(searchHits);
  }

}
